//
//  UIResponderAnalytics.swift
//
//  Created by Ink on 2024-03-15.
//

import Foundation

public protocol StatNormalPropertyProvider {
    var stat_normal_properties: [String: Any?] { get }
}


extension UIResponder {
    // 当前页面
    @objc open class var class_stat_page_name: String? { get { nil }}
}

public extension UIResponder {
    
    var stat_properties:[String:Any?]? {
        set{
            mUtilMap["stat_properties"] = newValue
        }
        get{
            var properties = mUtilMap["stat_properties"] as? [String:Any?]
            if properties == nil {
                if let provider = self as? StatNormalPropertyProvider {
                    properties = provider.stat_normal_properties
                }
                else {
                    properties = [:]
                }
                self.stat_properties = properties
            }
            // 修正事件来源上一页面
            properties?["route_source"] = StatManager.stat_route_source_path
            return properties
        }
    }
    
    @discardableResult
    func stat_properties_marge(_ properties: [String:Any?]?) -> Self{
        stat_properties = (stat_properties ?? [:]).merging(properties)
        return self
    }
    
    func statDidSelect(event: StatModel.EventType = .elementClick) {
        StatManager.stat(event: event,properties:stat_properties)
    }
    
    func statWillDisplay(event: StatModel.EventType = .elementShow) {
        StatManager.stat(event: event,properties:stat_properties)
    }
    
    func statElementClick(event: StatModel.EventType = .elementClick, properties:[String:Any?]? = nil) {
        StatManager.stat(event: event,properties:stat_properties_marge(properties).stat_properties)
    }
    
    func statElementShow(event: StatModel.EventType = .elementShow, properties:[String:Any?]? = nil) {
        StatManager.stat(event: event,properties:stat_properties_marge(properties).stat_properties)
    }
}

public extension UITableView {
    func statDidSelect(indexPath:IndexPath, event: StatModel.EventType = .elementClick) {
        cellForRow(at: indexPath)?.statDidSelect(event: event)
    }
}

public extension UICollectionView {
    func statDidSelect(indexPath:IndexPath, event: StatModel.EventType = .elementClick) {
        cellForItem(at: indexPath)?.statDidSelect(event: event)
    }
}

public protocol AnalyticsForForeground: NSObjectProtocol {
    
    var analyticsListViews:[UIView]? { get }
    
    func addStatWillEnterForegroundNotificationObserver()
    
    func removeStatWillEnterForegroundNotificationObserver()
    
    func analyticsPageShow()
    func analyticsListStatWillDisplay()
}
